import fs from 'node:fs';
import Seven from 'node-7z';
import path from 'node:path';
import AdmZip from 'adm-zip';
import { path7za } from '7zip-bin';
import { __path } from './path';
import { BrowserWindow } from 'electron';
import { writeResource } from './resource';
import { Resource } from '@type/WindowService';
import { readFile } from './file';

/**
 * 资源转zip文件
 */
export function resourceToZipFile(resource: Resource[]) {
	// 创建一个新的AdmZip实例
	const zip = new AdmZip();
	// 递归子函数
	function recursion(_path: string, resource: Resource[]) {
		resource.forEach((item) => {
			const curPath = __path.relative_join(false, _path, item.name);
			if (item.type === 'dir') {
				// 递归
				recursion(curPath, item.children);
			} else {
				// 添加一个文件
				zip.addFile(curPath, item.data);
			}
		});
	}

	recursion('', resource);

	return {
		zip,
		buffer: zip.toBuffer(),
	};
}

/**
 * 资源转7z文件
 */
export function resourceTo7zFile(resource: Resource[], win: BrowserWindow) {
	return new Promise<{buffer: Buffer}>(async (resolve, reject) => {
		const tempDir = __path.tempDir(); // 生成临时目录
		// 资源目录
		const resourcePaht = path.join(tempDir, 'resource');
		// 压缩文件路径
		const compressPath = path.join(tempDir, 'compress.7z');
		// 创建资源目录
		fs.mkdirSync(resourcePaht);

		try {
			// 写入临时目录
			await writeResource(resourcePaht, resource, win);
		} catch (error) {
			reject(error)
		}

		// 压缩成7z文件
		const seven = Seven.add(compressPath, path.join(resourcePaht, '*'), {
			$bin: path7za,
		});

		seven.on('end', () => {
			// 读取文件
			readFile(compressPath).then(res => {
				resolve({
					buffer: res.data,
				});
			})
		});

		seven.on('error', (err) => {
			reject(err)
		});
	});
}
